<template>
  <view class="container">
   
    
    <view v-if="loading" class="loading">
      <view class="loading-spinner"></view>
    </view>
    
    <view v-else class="form-container">
      <form @submit="submitForm">
        <view class="form-item">
          <view class="form-label required">标题</view>
          <input 
            class="form-input" 
            v-model="form.title" 
            placeholder="请输入反馈标题" 
            placeholder-class="placeholder"
          />
          <view v-if="errors.title" class="form-error">{{ errors.title }}</view>
        </view>
        
        <view class="form-item">
          <view class="form-label required">内容</view>
          <textarea 
            class="form-textarea" 
            v-model="form.content" 
            placeholder="请详细描述您遇到的问题或建议" 
            placeholder-class="placeholder"
          />
          <view v-if="errors.content" class="form-error">{{ errors.content }}</view>
        </view>
        
        <view class="form-item">
          <view class="form-label">图片</view>
          <view class="upload-box">
            <view 
              v-for="(item, index) in fileList" 
              :key="index" 
              class="upload-item"
            >
              <image :src="item.url" class="upload-image" mode="aspectFill"></image>
              <view class="upload-delete" @click="deletePic(index)">×</view>
            </view>
            
            <view 
              v-if="fileList.length < 9" 
              class="upload-add" 
              @click="chooseImage"
            >
              <text class="upload-add-icon">+</text>
            </view>
          </view>
        </view>
        
        <view class="submit-btn">
          <button class="btn btn-primary btn-block" form-type="submit">保存修改</button>
        </view>
      </form>
    </view>
  </view>
</template>

<script>
import { getFeedbackDetail, updateFeedback } from '@/api/services.js'

export default {
  data() {
    return {
      feedbackId: null,
      form: {
        title: '',
        content: '',
        media_urls: []
      },
      fileList: [],
      loading: true,
      errors: {
        title: '',
        content: ''
      }
    }
  },
  onLoad(options) {
    this.feedbackId = options.id
    this.loadFeedbackDetail()
  },
  methods: {
    navigateBack() {
      uni.navigateBack()
    },
    
    loadFeedbackDetail() {
      this.loading = true
      
      getFeedbackDetail(this.feedbackId)
        .then(res => {
          console.log('获取反馈详情响应:', res)
          if (res.code === 200) {
            const { title, content, media_urls } = res.data
            
            this.form.title = title
            this.form.content = content
            
            // 处理图片列表
            if (media_urls) {
              try {
                // 尝试解析JSON字符串，如果已经是数组则直接使用
                const parsedUrls = typeof media_urls === 'string' ? JSON.parse(media_urls) : media_urls
                this.form.media_urls = Array.isArray(parsedUrls) ? parsedUrls : []
                
                // 构建fileList
                this.fileList = this.form.media_urls.map(url => ({
                  url,
                  status: 'success'
                }))
              } catch (e) {
                console.error('解析media_urls失败:', e)
                this.form.media_urls = []
              }
            }
          } else {
            uni.showToast({
              title: res.message || '获取反馈详情失败',
              icon: 'none'
            })
          }
        })
        .catch(err => {
          console.error('获取反馈详情失败', err)
          uni.showToast({
            title: '获取反馈详情失败',
            icon: 'none'
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    validateForm() {
      let isValid = true
      this.errors = {
        title: '',
        content: ''
      }
      
      if (!this.form.title) {
        this.errors.title = '请输入反馈标题'
        isValid = false
      } else if (this.form.title.length < 2 || this.form.title.length > 50) {
        this.errors.title = '标题长度在2-50个字符之间'
        isValid = false
      }
      
      if (!this.form.content) {
        this.errors.content = '请输入反馈内容'
        isValid = false
      } else if (this.form.content.length < 5 || this.form.content.length > 500) {
        this.errors.content = '内容长度在5-500个字符之间'
        isValid = false
      }
      
      return isValid
    },
    
    chooseImage() {
      uni.chooseImage({
        count: 9 - this.fileList.length,
        success: (res) => {
          res.tempFilePaths.forEach(path => {
            // 这里应该调用上传API，上传成功后获取图片URL
            // 为简化示例，这里直接使用本地路径
            this.fileList.push({
              url: path,
              status: 'success'
            })
            
            // 更新表单数据
            this.form.media_urls.push(path)
          })
        }
      })
    },
    
    deletePic(index) {
      this.fileList.splice(index, 1)
      this.form.media_urls.splice(index, 1)
    },
    
    submitForm() {
      if (!this.validateForm()) return
      
      uni.showLoading({
        title: '保存中...'
      })
      
      // 将图片URL数组转换为JSON字符串
      const formData = {
        ...this.form,
        media_urls: JSON.stringify(this.form.media_urls)
      }
      
      updateFeedback(this.feedbackId, formData)
        .then(res => {
          uni.hideLoading()
          console.log('更新反馈响应:', res)
          
          if (res.code === 200) {
            uni.showToast({
              title: '保存成功',
              icon: 'success'
            })
            
            // 返回上一页
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          } else {
            uni.showToast({
              title: res.message || '保存失败',
              icon: 'none'
            })
          }
        })
        .catch(err => {
          uni.hideLoading()
          console.error('保存反馈失败', err)
          uni.showToast({
            title: '保存失败',
            icon: 'none'
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
}

.navbar {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
  padding: 0 30rpx;
  
  &-left {
    width: 60rpx;
    display: flex;
    align-items: center;
  }
  
  &-title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
  }
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 36rpx;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-back:before {
  content: "\e679";
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300rpx;
  
  &-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 6rpx solid #f3f3f3;
    border-top: 6rpx solid #3498db;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.form-container {
  padding: 20rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  
  &.required:after {
    content: '*';
    color: #fa3534;
    margin-left: 4rpx;
  }
}

.form-input, .form-textarea {
  width: 100%;
  background-color: #ffffff;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #eee;
  box-sizing: border-box;
}

.form-textarea {
  height: 200rpx;
}

.placeholder {
  color: #c0c4cc;
}

.form-error {
  font-size: 24rpx;
  color: #fa3534;
  margin-top: 6rpx;
}

.upload-box {
  display: flex;
  flex-wrap: wrap;
}

.upload-item, .upload-add {
  width: 200rpx;
  height: 200rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  position: relative;
}

.upload-image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.upload-delete {
  position: absolute;
  top: -16rpx;
  right: -16rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
  z-index: 1;
}

.upload-add {
  border: 1rpx dashed #dcdfe6;
  border-radius: 8rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f7f8fa;
}

.upload-add-icon {
  font-size: 60rpx;
  color: #c0c4cc;
}

.btn {
  font-size: 32rpx;
  padding: 20rpx;
  border-radius: 8rpx;
  border: none;
  color: #ffffff;
  
  &-primary {
    background-color: #2979ff;
  }
  
  &-block {
    width: 100%;
  }
}

.submit-btn {
  margin-top: 40rpx;
}
</style> 